package cn.melonlib.record.oper.comp.service;

import cn.hutool.core.util.NumberUtil;
import cn.melonlib.cores.commons.comp.utils.DateTimeUtils;
import cn.melonlib.cores.identification.comp.messenger.IdentificationMessenger;
import cn.melonlib.cores.jpa.comp.Dao;
import cn.melonlib.record.oper.model.entity.OperationRecord;
import cn.melonlib.record.oper.model.view.OperationRecordView;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.intellij.lang.annotations.Language;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Getter
public class OperationRecordSaveService extends ApplicationObjectSupport {

    @Resource
    private Dao dao;

    /**
     * 设置格式为<b>&lt;数字&gt;&lt;单位&gt</b> 当数字为负数时，永不过期，当数字为0时不记录日志;
     */
    @Value("${system.log.operation.expires:3d}")
    private String expires;


    @Resource
    private DateTimeUtils dateTimeUtils;

    @Resource
    private ObjectMapper jsonMapper;

    private final LinkedList<OperationRecord> cached=new LinkedList<>();

    public OperationRecord saveRecord(OperationRecord record){
        synchronized (cached) {
            long time = dateTimeUtils.expiresValue(expires);
            if(time>0) {
                cached.push(record);
                cached.notify();
            }
            return record;
        }
    }

    public OperationRecordView detail(String id){
        return new OperationRecordView(this.dao.getEntity(OperationRecord.class,NumberUtil.parseLong(id)),jsonMapper);
    }





    @Transactional(value = Transactional.TxType.REQUIRES_NEW,rollbackOn = Exception.class)
    public void storeLogs() throws Exception{
        System.out.println(Thread.currentThread().getId());
        long time = dateTimeUtils.expiresValue(expires);
        if (cached.size() > 0&&time != 0) {
            logger.info("开始保存请求日志>>>" + cached.size());
            cached.forEach(operationRecord -> {
                dao.save(operationRecord).getResult();
            });
            cached.clear();
            if(time >0) {
                @Language("HQL") String query = "delete from OperationRecord where createDateTime < ?1";
                int num = dao.updateQl(query, List.of(time));
                logger.info("清理掉过期日志>>>" + num);
            }
        }

    }
}
